//index.js
//获取应用实例
import request from '../../utils/request'
import Datetime from '../../utils/datetime'
import WxNotificationCenter from '../../utils/WxNotificationCenter'
const app = getApp()

Page({
  data: {
    account: {},
    albumsData: {
      results: []
    },
    isInited: false
  },
  onLoad: function () {
    if (app.globalData.loginToken) {
      // 初始化数据
      this.initData()
    } else {
      app.loginTokenReadyCallback = res => {
        // 初始化数据, 第一次进来要等待获取到token
        this.initData()
      }
    }
    if (app.globalData.account) {
      this.setData({
        account: app.globalData.account,
      })
    } else {
      // 由于 getAccount 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.accountReadyCallback = res => {
        this.setData({
          account: res.data
        })
      }
    }
    let that = this
    WxNotificationCenter.addNotification("refreshAlbums", that.initData, that)
    WxNotificationCenter.addNotification("refreshPosts", that.initData, that)
  },

  formSubmit: function (e) {
    if (e.detail) {
      app.uploadFormId(e.detail.formId, function (err){})
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 刷新页面
    if (app.globalData.needRefresh) {
      this.initData(function() {
        app.globalData.needRefresh = false
      })
    }
  },

  /*
   * 页面下拉刷新
   */
  onPullDownRefresh: function () {
    wx.showLoading({
      title: '刷新中...',
    })
    this.initData(function () {
      wx.hideLoading()
      wx.stopPullDownRefresh()
    })
  },

  /*
   * 页面上拉触底
   */
  onReachBottom: function() {
    this.loadMore()
  },

  viewUser: function() {
    wx.navigateTo({
      url: '/pages/user/index',
    })
  },
  createAlbum: function() {
    wx.navigateTo({
      url: '/pages/album/create',
    })
  },
  viewAlbum: function (e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/album/index?id=' + id,
    })
  },
  uploadPic: function() {
    wx.navigateTo({
      url: '/pages/album/upload',
    })
  },

  /*
   * 初始化数据
   */
  initData(callback) {
    let that = this
    let url = app.globalData.apiHost + '/albums/'
    request(url, 'GET', app.globalData.loginToken, {}, function(err, data) {
      console.log(data)
      if (!err) {
        that._setDatetime(data)
        that.setData({ albumsData: data, isInited: true })
        app.globalData.albums = data.results
      } else {
        that.setData({ isInited: true })
      }
      if (callback) {
        return callback()
      }
    })
  },

  /*
   * 加载更多数据
   */
  loadMore() {
    let that = this
    let albumsData = this.data.albumsData
    if (albumsData.next) {
      request(albumsData.next, 'GET', app.globalData.loginToken, {}, function(err, data) {
        if (!err) {
          that._setDatetime(data)
          albumsData.next = data.next
          albumsData.previous = data.previous
          albumsData.results = albumsData.results.concat(data.results)
          that.setData({ albumsData: albumsData })
          app.globalData.albums = albumsData.results
        }
      })
    }
  },

  /*
   * 操作时间
   */
  _setDatetime(data) {
    for (let i = 0; i < data.results.length; i++) {
      let item = data.results[i]
      let datetime = new Datetime(item.created)
      item.createTime = datetime.getDateStr()
    }
  },

  /*
   * 查看图片大图
   */
  viewImages: function (e) {
    let albumIndex = parseInt(e.currentTarget.dataset.albumindex)
    let imgIndex = parseInt(e.currentTarget.dataset.index)
    let album = this.data.albumsData.results[albumIndex]
    let images = []
    let currentImg = ''
    for (let i = 0; i < album.attachments.length; i++) {
      let item = album.attachments[i]
      if (item.file_type == 0) {
        images.push(item.file)
      }
      if (imgIndex == i) {
        currentImg = item.file
      }
    }

    wx.previewImage({
      urls: images,
      current: currentImg
    })
  },

  /*
   * 播放视频
   */
  playVideo: function (e) {
    console.log('video')
    let albumIndex = parseInt(e.currentTarget.dataset.albumindex)
    let videoIndex = parseInt(e.currentTarget.dataset.index)
    let album = this.data.albumsData.results[albumIndex]
    let videoId = 'video_' + albumIndex + '_' + videoIndex
    this.videoCtx = wx.createVideoContext(videoId)
    this.videoCtx.play()
    this.videoCtx.requestFullScreen()
  },

  /*
   * 视频播放暂停
   */
  videoPause: function () {
    console.log('videoPause')
  },

  /*
   * 视频全屏事件
   */
  videoFullScreenChange: function (e) {
    if (!e.detail.fullScreen) {
      this.videoCtx.pause()
    }
  },

})
